--- 模块功能：MQTT客户端数据接收处理
-- @author openLuat
-- @module mqtt.mqttInMsg
-- @license MIT
-- @copyright openLuat
-- @release 2018.03.28
module(..., package.seeall)

require "config"
require "nvm"
require "earthquakeWaring"
require "earthquakeWaringDril"
require "logGenerator"
require "audio"

-- 参数配置文件初始化
nvm.init("config.lua", true)

-- nvm参数获取
local fastCount, eqrTopic, topic = nvm.get("fastCount"), nvm.get("eqrTopic"),
                                   nvm.get("topic")
-- 变量初始化
local slen, errInfo, sysTime, action, acountSuspend = string.len, "", "", false,
                                                      0
local setGpio9Fnc = pins.setup(pio.P0_9, 1) -- 静音设置（高电平静音）
-- 速报播报
local function eqrBroadcast(tjsondataGet)
    local strBroadCast, broadCastCount = "", fastCount
    local msgID, msgType, eventID, locName, epiLat, epiLon, focdepth, magnitude,
          oriTime, listDate, listTime
    if tjsondataGet["MsgID"] then
        msgID = tjsondataGet["MsgID"]
        strBroadCast = strBroadCast .. "消息ID:" .. msgID
    end
    if tjsondataGet["MsgType"] then
        msgType = tjsondataGet["MsgType"]
        strBroadCast = strBroadCast .. ",消息类型:" .. msgType
    end
    if tjsondataGet["EventID"] then
        eventID = tjsondataGet["EventID"]
        strBroadCast = strBroadCast .. ",地震事件ID:" .. eventID
    end
    if tjsondataGet["Locname"] then
        locName = tjsondataGet["Locname"]
        strBroadCast = strBroadCast .. ",地名:" .. locName
    end
    if tjsondataGet["EpiLat"] then
        epiLat = tjsondataGet["EpiLat"]
        strBroadCast = strBroadCast .. ",震中纬度:" .. epiLat
    end
    if tjsondataGet["EpiLon"] then
        epiLon = tjsondataGet["EpiLon"]
        strBroadCast = strBroadCast .. ",震中经度:" .. epiLon
    end
    if tjsondataGet["Focdepth"] then
        focdepth = tjsondataGet["Focdepth"]
        strBroadCast = strBroadCast .. ",深度:" .. focdepth
    end
    if tjsondataGet["Magnitude"] then
        magnitude = tjsondataGet["Magnitude"]
        strBroadCast = strBroadCast .. ",震级:" .. magnitude
    end
    if tjsondataGet["Oritime"] then
        oriTime = tjsondataGet["Oritime"]
        listDate = string.split(string.split(oriTime, " ")[1], "-")
        listTime = string.split(string.split(oriTime, " ")[2], ":")
        strBroadCast =
            strBroadCast .. ",发震时间:" .. listDate[1] .. "年" ..
                listDate[2] .. "月" .. listDate[3] .. "日," .. listTime[1] ..
                "时" .. listTime[2] .. "分" .. listTime[3] .. "秒"
    end
    while broadCastCount > 0 do
        setGpio9Fnc(0)
        audio.play(TTS, "TTS", strBroadCast, 7)
        broadCastCount = broadCastCount - 1
        sys.wait(1000)
    end
    setGpio9Fnc(1)
end

--- MQTT客户端数据接收处理
-- @param mqttRClient，MQTT客户端对象
-- @return 处理成功返回true，处理出错返回false
-- @usage mqttInMsg.proc(mqttRClient)
function proc(mqttRClient)
    local result, data, receiveMsg
    while true do
        sysTime = string.format("%04d-%02d-%02d %02d:%02d:%02d",
                                os.date("*t").year, os.date("*t").month,
                                os.date("*t").day, os.date("*t").hour,
                                os.date("*t").min, os.date("*t").sec)
        result, data = mqttRClient:receive(60000, "APP_SOCKET_SEND_DATA")
        errInfo = ""
        log.info("procResult:", result, "procData:", data)
        -- 接收到数据
        if result then
            receiveMsg = data.payload
            local tjsondata, resultMqtt, errinfo = json.decode(receiveMsg)
            --[[ if eqrTopic == data.topic then
                if resultMqtt and type(tjsondata) == "table" then
                    if fastCount > 0 then
                        sys.taskInit(eqrBroadcast, tjsondata)
                    elseif fastCount == 0 then
                        errInfo = errInfo .. "[" .. sysTime .. "]" ..
                                      "速报信息播报次数为0" .. "\n"
                    end
                else
                    errInfo = errInfo .. "[" .. sysTime .. "]" ..
                                  "[速报json报文解析错误:]" .. errinfo ..
                                  "\n"
                end
            end ]]
            if topic == data.topic or "EEW/JSON/DRILL/KSCONNTEST" == data.topic then
                if resultMqtt and type(tjsondata) == "table" then
                    earthquakeWaring.EarthquakeWarning(receiveMsg, tjsondata,
                                                       data.topic)
                else
                    errInfo = errInfo .. "[" .. sysTime .. "]" ..
                                  "[地震预警信息json报文解析报错:]" ..
                                  errinfo .. "\n"
                end
            end
        else
            break
        end
    end
    errInfo = errInfo .. "[" .. sysTime .. "]" ..
                  "[mqttInMsgQuakeInfoRel 返回结果:]" .. tostring(result) .. "data:" ..
                  tostring(data) .. "\n"
    if slen(errInfo) > 0 then logGenerator.generateLogTask(errInfo, "log") end
    log.info("MQTT INMSG QU TASK CENT  RESULT", tostring(result),
             "MQTT INMSG QU TASK CENT DATA", data)
    return result or data == "timeout" or data == "APP_SOCKET_SEND_DATA"
end
